// 清空标签
function clearBookmarks() {
  chrome.bookmarks.getTree((re) => {
    removeall(re);
    chrome.notifications.create(null, {
      type: 'basic',
      iconUrl: 'img/icon.png',
      title: '书签',
      message: '清空完毕'
    })
  })
}

// 统计书签个数
function countBookmarks(element) {
  chrome.bookmarks.getTree((re) => {
    var n = counted(re, 0);
    element.innerText = n
  })
}

function counted(data, num) {
  data.forEach((v) => {
    if (v.url === undefined) {
      num = counted(v.children, num)
    } else {
      num += 1
    }
  })
  return num
}

// 清空三级目录或书签信息
function removeall(data) {
  data[0].children.forEach((v) => {
    v.children.forEach((vv) => {
      if (vv.url === undefined) {
        chrome.bookmarks.removeTree(vv.id, function (rs) { })
      } else {
        chrome.bookmarks.remove(vv.id, function (rs) { })
      }
    })
  })
}

// 递归全量导入
// bookmark ( object )
// parentId ( optional string )
// Defaults to the Other Bookmarks folder.
// index ( optional integer )
// title ( optional string )
// url ( optional string )
function addAll(data, parentname) {
  data.forEach((v) => {
    if (parentname === '') {
      if (v.children !== undefined) {
        addAll(v.children, v.id)
      } else {
        var tmp = {
          parentId: v.id,
          title: v.title,
          url: v.url
        }
        chrome.bookmarks.create(tmp, function (rrs) { })
      }
    } else {
      if (v.children !== undefined) {
        var tmp = {
          parentId: parentname,
          title: v.title
        }
        // Unchecked runtime.lastError: Can't find parent bookmark for id.
        chrome.bookmarks.create(tmp, function (rs) {
          addAll(v.children, rs.id)
        })
      } else {
        var tmp = {
          parentId: parentname,
          title: v.title,
          url: v.url
        }
        chrome.bookmarks.create(tmp, function (rrs) { })
      }
    }
  })
}

function getDate() {
  let myDate = new Date()
  let year = myDate.getFullYear()
  let month = myDate.getMonth() + 1
  let date = myDate.getDate()
  let h = myDate.getHours()
  let m = myDate.getMinutes()
  let s = myDate.getSeconds()
  let now = year + '-' + conver(month) + '-' + conver(date) + ' ' + conver(h) + ':' + conver(m) + ':' + conver(s)
  return now
}

//日期时间处理
function conver(s) {
  return s < 10 ? '0' + s : s
}

// // onChanged自动提交
// chrome.bookmarks.onChanged.addListener(function (id, changeInfo) {
//   // alert('onChnage ' + id);
//   chrome.storage.local.get(['reponame', 'repostatus'], (result) => {
//     //   alert('status '+result.reponame+' ' + result.repostatus)
//     if (result.reponame !== undefined && result.repostatus !== false) {
//       let github = new Gitee()
//       github.updateTags('bookmarks/' + result.reponame, getDate(), 'master')
//     }
//   })
// });

// // onCreated自动提交
// chrome.bookmarks.onCreated.addListener(function (id, bookmark) {
//   // alert('onCreated ' + id);
//   chrome.storage.local.get(['reponame', 'repostatus'], (result) => {
//     //   alert('status '+result.reponame+' ' + result.repostatus)
//     if (result.reponame !== undefined && result.repostatus !== false) {
//       let github = new Gitee()
//       github.updateTags('bookmarks/' + result.reponame, getDate(), 'master')
//     }
//   })
// });

// // onChildrenReordered自动提交
// chrome.bookmarks.onChildrenReordered.addListener(function (id, reorderInfo) {
//   // alert('onChildrenReordered ' + id);
//   chrome.storage.local.get(['reponame', 'repostatus'], (result) => {
//     //   alert('status '+result.reponame+' ' + result.repostatus)
//     if (result.reponame !== undefined && result.repostatus !== false) {
//       let github = new Gitee()
//       github.updateTags('bookmarks/' + result.reponame, getDate(), 'master')
//     }
//   })
// });

// // onRemoved自动提交
// chrome.bookmarks.onRemoved.addListener(function (id, removeInfo) {
//   // alert('onRemoved ' + id);
//   chrome.storage.local.get(['reponame', 'repostatus'], (result) => {
//     //   alert('status '+result.reponame+' ' + result.repostatus)
//     if (result.reponame !== undefined && result.repostatus !== false) {
//       let github = new Gitee()
//       github.updateTags('bookmarks/' + result.reponame, getDate(), 'master')
//     }
//   })
// });

/* 
  ======================  防止更新书签时，过于频繁的触发自动上次事件  ================
*/

function updateTags(id, removeInfo) {
  chrome.storage.local.get(['reponame', 'repostatus'], (result) => {
    if (result.reponame !== undefined && result.repostatus !== false) {
      let github = new Gitee()
      github.updateTags('bookmarks/' + result.reponame, getDate(), 'master')
    }
  })
}

// ------------------------防抖---------------------------
let timeout = null; // 创建一个标记用来存放定时器的返回值。放在外面是让onChanged、onCreated等方法公用同一个计时器
var debounce = (fn, ...args) => {
  return function () {
    // console.log(timeout)
    // console.log(this);
    clearTimeout(timeout); // 保证用户输入完之后只有一个setTimeout
    timeout = setTimeout(() => {
      fn.call(this, arguments, args);
    }, 20 * 1000);
  };
}

chrome.bookmarks.onChanged.addListener(debounce(updateTags))
chrome.bookmarks.onCreated.addListener(debounce(updateTags))
chrome.bookmarks.onChildrenReordered.addListener(debounce(updateTags))
chrome.bookmarks.onRemoved.addListener(debounce(updateTags))